import React, { useState, useRef } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faImage, faMusic, faConvert, faDownload, faFileAudio, faFileImage, faSpinner } from '@fortawesome/free-solid-svg-icons';
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';

const ffmpeg = createFFmpeg({
  log: true,
  mainName: 'main',
  corePath: 'https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.js',
  wasmPath: 'https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.wasm',
  workerPath: 'https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.worker.js',
});

function App() {
  const [imageFile, setImageFile] = useState(null);
  const [audioFile, setAudioFile] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isConverting, setIsConverting] = useState(false);
  const [conversionProgress, setConversionProgress] = useState(0);
  const [outputUrl, setOutputUrl] = useState(null);
  const [errorMessage, setErrorMessage] = useState('');
  const [isDragging, setIsDragging] = useState({ image: false, audio: false });

  // 初始化FFmpeg
  const initFFmpeg = async () => {
    if (!ffmpeg.isLoaded()) {
      setIsLoading(true);
      try {
        await ffmpeg.load();
      } catch (error) {
        setErrorMessage('加载FFmpeg失败，请刷新页面重试。');
        console.error('Failed to load FFmpeg:', error);
      } finally {
        setIsLoading(false);
      }
    }
  };

  // 处理图片上传
  const handleImageUpload = (file) => {
    if (file && file.type.startsWith('image/')) {
      setImageFile(file);
      setErrorMessage('');
    } else {
      setErrorMessage('请上传有效的图片文件。');
    }
  };

  // 处理音频上传
  const handleAudioUpload = (file) => {
    if (file && file.type === 'audio/mpeg') {
      setAudioFile(file);
      setErrorMessage('');
    } else {
      setErrorMessage('请上传有效的MP3音频文件。');
    }
  };

  // 处理转换
  const handleConvert = async () => {
    if (!imageFile || !audioFile) {
      setErrorMessage('请先上传背景图片和音频文件。');
      return;
    }

    if (!ffmpeg.isLoaded()) {
      await initFFmpeg();
    }

    if (!ffmpeg.isLoaded()) {
      return;
    }

    setIsConverting(true);
    setConversionProgress(0);
    setErrorMessage('');

    try {
      // 写入文件到FFmpeg虚拟文件系统
      ffmpeg.FS('writeFile', 'image.jpg', await fetchFile(imageFile));
      ffmpeg.FS('writeFile', 'audio.mp3', await fetchFile(audioFile));

      // 设置进度回调
      ffmpeg.setProgress(({ ratio }) => {
        setConversionProgress(Math.round(ratio * 100));
      });

      // 执行转换命令
      await ffmpeg.run(
        '-loop', '1',
        '-i', 'image.jpg',
        '-i', 'audio.mp3',
        '-c:v', 'libx264',
        '-tune', 'stillimage',
        '-c:a', 'aac',
        '-b:a', '192k',
        '-pix_fmt', 'yuv420p',
        '-shortest',
        'output.mp4'
      );

      // 读取输出文件
      const data = ffmpeg.FS('readFile', 'output.mp4');
      const blob = new Blob([data.buffer], { type: 'video/mp4' });
      const url = URL.createObjectURL(blob);
      setOutputUrl(url);

    } catch (error) {
      setErrorMessage('转换失败，请重试。错误：' + error.message);
      console.error('Conversion error:', error);
    } finally {
      setIsConverting(false);
      setConversionProgress(0);
    }
  };

  // 处理下载
  const handleDownload = () => {
    if (outputUrl) {
      const a = document.createElement('a');
      a.href = outputUrl;
      a.download = 'output.mp4';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  };

  // 清理资源
  React.useEffect(() => {
    return () => {
      if (outputUrl) {
        URL.revokeObjectURL(outputUrl);
      }
    };
  }, [outputUrl]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 p-4 md:p-8">
      <div className="max-w-5xl mx-auto">
        {/* 标题部分 */}
        <header className="text-center mb-12">
          <h1 className="text-4xl md:text-5xl font-bold text-primary mb-4">MP3转MP4视频转换器</h1>
          <p className="text-gray-600 text-lg">上传背景图片和MP3音频，一键转换为视频文件</p>
        </header>

        {/* 错误消息 */}
        {errorMessage && (
          <div className="bg-error/10 border border-error text-error p-4 rounded-lg mb-6 animate-shake">
            {errorMessage}
          </div>
        )}

        {/* 主要内容区域 */}
        <main className="space-y-8">
          {/* 文件上传区域 */}
          <div className="grid md:grid-cols-2 gap-8">
            {/* 图片上传区 */}
            <div 
              className={`
                border-2 border-dashed rounded-xl p-8 text-center transition-all duration-300
                ${isDragging.image ? 'border-primary bg-primary/5' : 'border-gray-300 hover:border-primary hover:bg-primary/5'}
                ${imageFile ? 'border-success bg-success/5' : ''}
              `}
              onDragOver={(e) => {
                e.preventDefault();
                setIsDragging(prev => ({ ...prev, image: true }));
              }}
              onDragLeave={() => setIsDragging(prev => ({ ...prev, image: false }))}
              onDrop={(e) => {
                e.preventDefault();
                setIsDragging(prev => ({ ...prev, image: false }));
                if (e.dataTransfer.files.length > 0) {
                  handleImageUpload(e.dataTransfer.files[0]);
                }
              }}
              onClick={() => document.getElementById('image-upload').click()}
            >
              <input
                id="image-upload"
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  if (e.target.files.length > 0) {
                    handleImageUpload(e.target.files[0]);
                  }
                }}
              />
              {imageFile ? (
                <div className="space-y-4">
                  <div className="flex justify-center">
                    <div className="relative w-40 h-40 rounded-lg overflow-hidden border-4 border-white shadow-lg">
                      <img 
                        src={URL.createObjectURL(imageFile)} 
                        alt="上传的背景图片"
                        className="w-full h-full object-cover"
                      />
                    </div>
                  </div>
                  <div>
                    <div className="inline-flex items-center px-3 py-1 rounded-full bg-success/20 text-success text-sm font-medium">
                      <FontAwesomeIcon icon={faFileImage} className="mr-1" />
                      {imageFile.name}
                    </div>
                  </div>
                  <button 
                    className="text-gray-500 hover:text-error transition-colors"
                    onClick={(e) => {
                      e.stopPropagation();
                      setImageFile(null);
                    }}
                  >
                    更换图片
                  </button>
                </div>
              ) : (
                <div className="space-y-4">
                  <FontAwesomeIcon icon={faImage} size="4x" className="text-gray-400 mx-auto" />
                  <h3 className="text-xl font-semibold text-gray-700">上传背景图片</h3>
                  <p className="text-gray-500 mb-4">点击或拖放图片到此处</p>
                  <p className="text-xs text-gray-400">支持 JPG、PNG、WebP 等格式</p>
                </div>
              )}
            </div>

            {/* 音频上传区 */}
            <div 
              className={`
                border-2 border-dashed rounded-xl p-8 text-center transition-all duration-300
                ${isDragging.audio ? 'border-primary bg-primary/5' : 'border-gray-300 hover:border-primary hover:bg-primary/5'}
                ${audioFile ? 'border-success bg-success/5' : ''}
              `}
              onDragOver={(e) => {
                e.preventDefault();
                setIsDragging(prev => ({ ...prev, audio: true }));
              }}
              onDragLeave={() => setIsDragging(prev => ({ ...prev, audio: false }))}
              onDrop={(e) => {
                e.preventDefault();
                setIsDragging(prev => ({ ...prev, audio: false }));
                if (e.dataTransfer.files.length > 0) {
                  handleAudioUpload(e.dataTransfer.files[0]);
                }
              }}
              onClick={() => document.getElementById('audio-upload').click()}
            >
              <input
                id="audio-upload"
                type="file"
                accept=".mp3"
                className="hidden"
                onChange={(e) => {
                  if (e.target.files.length > 0) {
                    handleAudioUpload(e.target.files[0]);
                  }
                }}
              />
              {audioFile ? (
                <div className="space-y-4">
                  <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 mb-2">
                    <FontAwesomeIcon icon={faMusic} size="2x" className="text-primary" />
                  </div>
                  <div>
                    <div className="inline-flex items-center px-3 py-1 rounded-full bg-success/20 text-success text-sm font-medium">
                      <FontAwesomeIcon icon={faFileAudio} className="mr-1" />
                      {audioFile.name}
                    </div>
                  </div>
                  <div className="text-sm text-gray-500">
                    {(audioFile.size / (1024 * 1024)).toFixed(2)} MB
                  </div>
                  <button 
                    className="text-gray-500 hover:text-error transition-colors"
                    onClick={(e) => {
                      e.stopPropagation();
                      setAudioFile(null);
                    }}
                  >
                    更换音频
                  </button>
                </div>
              ) : (
                <div className="space-y-4">
                  <FontAwesomeIcon icon={faMusic} size="4x" className="text-gray-400 mx-auto" />
                  <h3 className="text-xl font-semibold text-gray-700">上传MP3音频</h3>
                  <p className="text-gray-500 mb-4">点击或拖放MP3文件到此处</p>
                  <p className="text-xs text-gray-400">仅支持 MP3 格式</p>
                </div>
              )}
            </div>
          </div>

          {/* 转换按钮和进度区域 */}
          <div className="text-center space-y-6">
            {isLoading ? (
              <div className="flex flex-col items-center space-y-4">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary" />
                <p className="text-gray-600">正在加载转换引擎...</p>
              </div>
            ) : isConverting ? (
              <div className="space-y-6">
                <div className="space-y-2">
                  <p className="text-lg font-medium text-gray-700">正在转换视频...</p>
                  <div className="w-full bg-gray-200 rounded-full h-3">
                    <div 
                      className="bg-primary h-3 rounded-full transition-all duration-300 ease-out"
                      style={{ width: `${conversionProgress}%` }}
                    />
                  </div>
                  <p className="text-sm text-gray-500">{conversionProgress}%</p>
                </div>
              </div>
            ) : outputUrl ? (
              <div className="space-y-4">
                <div className="inline-flex items-center px-4 py-2 rounded-full bg-success/20 text-success">
                  <span className="text-lg font-medium mr-2">✓</span>
                  转换完成！
                </div>
                <button 
                  onClick={handleDownload}
                  className="inline-flex items-center px-6 py-3 bg-success text-white rounded-lg hover:bg-success/90 focus:ring-4 focus:ring-success/30 transition-all transform hover:scale-105"
                >
                  <FontAwesomeIcon icon={faDownload} className="mr-2" />
                  下载MP4视频
                </button>
                <button 
                  onClick={() => setOutputUrl(null)}
                  className="text-gray-500 hover:text-error transition-colors"
                >
                  重新开始
                </button>
              </div>
            ) : (
              <button 
                onClick={handleConvert}
                disabled={!imageFile || !audioFile}
                className={`
                  inline-flex items-center px-8 py-4 text-lg font-semibold rounded-xl transition-all transform hover:scale-105
                  ${imageFile && audioFile 
                    ? 'bg-primary text-white hover:bg-primary/90 focus:ring-4 focus:ring-primary/30 shadow-lg'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'}
                `}
              >
                <FontAwesomeIcon icon={faConvert} className="mr-2" />
                开始转换
              </button>
            )}
          </div>
        </main>

        {/* 页脚 */}
        <footer className="mt-16 text-center text-gray-500 text-sm">
          <p>MP3转MP4视频转换器 &copy; {new Date().getFullYear()}</p>
          <p className="mt-1">所有处理均在您的浏览器中进行，不会上传到服务器</p>
        </footer>
      </div>
    </div>
  );
}

export default App;